<template>
    <div class="order_list_container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @select="onSelect"
            @selection-change="onSelectionChange"
            @select-all="onSelectAll">
            <template #headerOperate>
                <el-button plain @click="router.push('/salesleads/salesmanagement/ordermanagement/setting')"
                    >高级设置</el-button
                >
                <el-button type="primary" @click="router.push('/salesleads/salesmanagement/ordermanagement/neworder')"
                    >新建订单</el-button
                >
            </template>
        </ZwTable>
    </div>
    <!-- 删除弹框 -->
    <ZWDeletdialog ref="DeletdialogRef" @submit="onSubmit" />
</template>

<script setup lang="tsx">
import { reactive, ref, onMounted, computed, watch, nextTick, onActivated } from 'vue';
import useClipboard from 'vue-clipboard3';
import { ElMessage, ElImage, ElPopover, ElButton, ElIcon } from 'element-plus';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import { orderGetList, auditSubmit } from '@/api/salesleads/ordermanagement/orderlist';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import { useRouter } from 'vue-router';
import { deepCopy } from '@/utils/helper';
import { tableH, reSize } from '@/utils/utils';
const DeletdialogRef: any = ref(null);
const router = useRouter();
const checkList = ref([]);
const delId = ref('');

const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);

const props = defineProps(['activeName']);

const defaultParams = {
    state: -1, //审核状态 1：待审核 2：已审核3：不通过
    product_name: '', //产品名称
    order_no: '',
    cust_name: '', //客户名称
    business_opportunity_name: '', //商机名称
    belong_uid: [], //所属员工id
    pay_state: '-1', //订单状态 1：未付款 2：已付款
    creat_time: []
};
// 复制
const { toClipboard } = useClipboard();
const onCopy = async (v: any) => {
    try {
        await toClipboard(v);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};
const popStyle = {
    width: '227px',
    height: '48px',
    ['border-radius']: '2px',
    padding: '6px',
    border: '1px solid #eaeaea',
    display: 'flex',
    ['align-items']: 'center',
    margin: '5px 0'
};
const style = {
    ['font-size']: '12px',
    color: '#969696'
};
const tableRef = ref<any>(null);

const state = reactive({
    searchParams: deepCopy(defaultParams),
    searchHeight: '160px'
});
const searchOption = computed(() => {
    return [
        {
            label: '产品名称',
            name: 'product_name',
            value: '',
            type: 'input',
            placeholder: '请输入产品名称'
        },
        {
            label: '订单编号',
            name: 'order_no',
            value: '',
            type: 'input',
            placeholder: '请输入订单编号'
        },
        {
            label: '客户名称',
            name: 'cust_name',
            value: '',
            type: 'input',
            placeholder: '请输入客户名称'
        },
        {
            label: '商机名称',
            name: 'business_opportunity_name',
            value: '',
            type: 'input',
            placeholder: '请输入商机名称'
        },
        {
            label: '所属员工',
            name: 'belong_uid',
            value: [],
            type: 'select',
            placeholder: '请选择所属员工',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '订单状态',
            name: 'pay_state',
            value: '',
            type: 'select',
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve([
                            { name: '全部', id: -1 },
                            { name: '未付款', id: 1 },
                            { name: '已付款', id: 2 }
                        ]);
                    }, 100);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '审核状态',
            name: 'state',
            value: '',
            type: 'select',
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { name: '全部', id: -1 },
                        { name: '待审核', id: 1 },
                        { name: '已审核', id: 2 },
                        { name: '不通过', id: 3 }
                    ]);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '下单时间',
            name: 'creat_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
});
const search = (v: any) => {
    state.searchParams = {
        ...deepCopy(defaultParams),
        ...v
    };
    currentParams.value = v;
};
const reset = (v: any) => {
    state.searchParams = { ...deepCopy(defaultParams) };
    currentParams.value = null;
};
/**
 * @description: 展开收起
 */
const expandHandle = (expand: boolean) => {
    state.searchHeight = expand ? '160px' : '64px';
};

const rowData = ref<any>({});
const onAudit = (row: any) => {
    rowData.value = row;
    DeletdialogRef.value.appDialog.title = '提交审核';
    DeletdialogRef.value.content = '您确定要提交审核吗？';
    DeletdialogRef.value.appDialog.visible = true;
};
const onSubmit = () => {
    auditSubmit({ order_id: rowData.value.id }).then(() => {
        ElMessage.success('提交审核成功');
        tableRef.value.reload();
    });
};

const onBtn = (row: any) => {
    switch (row.state) {
        case 0:
            return (
                <>
                    <ElButton
                        size="small"
                        onClick={() => {
                            router.push({
                                path: '/salesleads/salesmanagement/ordermanagement/neworder',
                                query: { type: 'look', id: row.id }
                            });
                        }}>
                        查看
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => {
                            router.push({
                                path: '/salesleads/salesmanagement/ordermanagement/neworder',
                                query: { type: 'edit', id: row.id }
                            });
                        }}>
                        编辑
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => {
                            router.push({
                                path: '/salesleads/salesmanagement/ordermanagement/detail',
                                query: { id: row.id }
                            });
                        }}>
                        详情
                    </ElButton>
                </>
            );
        case 1:
            return (
                <>
                    <ElButton
                        size="small"
                        onClick={() => {
                            router.push({
                                path: '/salesleads/salesmanagement/ordermanagement/neworder',
                                query: { type: 'look', id: row.id }
                            });
                        }}>
                        查看
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => {
                            router.push({
                                path: '/salesleads/salesmanagement/ordermanagement/detail',
                                query: { id: row.id }
                            });
                        }}>
                        详情
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => {
                            onAudit(row);
                        }}>
                        提交审核
                    </ElButton>
                </>
            );
        case 2:
            return (
                <>
                    <ElButton
                        size="small"
                        onClick={() => {
                            router.push({
                                path: '/salesleads/salesmanagement/ordermanagement/neworder',
                                query: { type: 'look', id: row.id }
                            });
                        }}>
                        查看
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => {
                            router.push({
                                path: '/salesleads/salesmanagement/ordermanagement/detail',
                                query: { id: row.id }
                            });
                        }}>
                        详情
                    </ElButton>
                </>
            );
        case 3:
            return (
                <>
                    <ElButton
                        size="small"
                        onClick={() => {
                            router.push({
                                path: '/salesleads/salesmanagement/ordermanagement/neworder',
                                query: { type: 'look', id: row.id }
                            });
                        }}>
                        查看
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => {
                            router.push({
                                path: '/salesleads/salesmanagement/ordermanagement/neworder',
                                query: { type: 'edit', id: row.id }
                            });
                        }}>
                        编辑
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => {
                            router.push({
                                path: '/salesleads/salesmanagement/ordermanagement/detail',
                                query: { id: row.id }
                            });
                        }}>
                        详情
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => {
                            onAudit(row);
                        }}>
                        提交审核
                    </ElButton>
                </>
            );
    }
};
// 表格
const tableOption = [
    {
        prop: 'order_no',
        label: '订单编号',
        width: 320
    },
    {
        prop: 'business_opportunity_name',
        label: '关联商机',
        width: 200
    },
    {
        prop: 'qr_code_link',
        label: '产品列表',
        width: 200,
        render({ row, column, index }) {
            const slotError = () => (
                <div class="image-slot" style="font-size:48px">
                    <ElIcon>
                        <IconPicture />
                    </ElIcon>
                </div>
            );
            const slotReference = () => (
                <div>
                    {row.product.map((item: any, index: any) => {
                        if (index <= 1) {
                            return (
                                <div class="imgslist">
                                    <div>
                                        <ElImage
                                            src={item.url}
                                            style="width: 48px; height: 48px;"
                                            vSlots={{ error: slotError }}
                                        />
                                    </div>
                                    <div class="name">
                                        <p>{item.product_name}</p>
                                        <p class="many">
                                            ￥{item.buy_price}*{item.buy_qty}
                                        </p>
                                    </div>
                                </div>
                            );
                        }
                    })}
                </div>
            );
            const slotDefault = () => (
                <div>
                    {row.product.map((item: any) => {
                        return (
                            <div style="display: flex;">
                                <div style="margin-right:5px;">
                                    <ElImage
                                        src={item.url}
                                        style="width: 48px; height: 48px;"
                                        vSlots={{ error: slotError }}
                                    />
                                </div>
                                <div class="name">
                                    <p>{item.product_name}</p>
                                    <p class="many">
                                        ￥{item.buy_price}*{item.buy_qty}
                                    </p>
                                </div>
                            </div>
                        );
                    })}
                </div>
            );
            return (
                <ElPopover
                    popper-class="popGroup"
                    trigger="hover"
                    vSlots={{ reference: slotReference, default: slotDefault }}
                    width={300}
                    popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"></ElPopover>
            );
        }
    },
    {
        prop: 'order_amount',
        label: '订单金额',
        width: 130,
        render({ row, column, index }) {
            return <>￥{row.order_amount}</>;
        }
    },
    {
        prop: 'pay_state_name',
        label: '订单状态',
        width: 130
    },
    {
        prop: 'state_name',
        label: '审核状态',
        width: 130,
        render({ row, column, index }) {
            return <>{row.state_name || '--'}</>;
        }
    },
    {
        prop: 'audit_message',
        label: '原因',
        width: 130,
        render({ row, column, index }) {
            return <>{row.audit_message || '--'}</>;
        }
    },
    {
        prop: 'cust_name',
        label: '客户信息',
        width: 200,
        showOverflowTooltip: true
    },
    {
        prop: 'contacts',
        label: '联系人',
        width: 200,
        render({ row, column, index }) {
            let str = '';
            row.contacts.forEach((item: any) => {
                str += item.name + '，';
            });
            str = str.slice(0, -1);
            return (
                <>
                    {str.length > 12 ? (
                        <el-tooltip effect="dark" content={str} placement="top-start">
                            <div class="contacts"> {str}</div>
                        </el-tooltip>
                    ) : (
                        <div class="contacts">{str || '--'}</div>
                    )}
                </>
            );
        }
    },
    {
        prop: 'source_name',
        label: '订单来源',
        width: 130
    },
    {
        prop: 'remark',
        label: '备注',
        width: 200,
        render({ row, column, index }) {
            return <>{row.remark || '--'}</>;
        }
    },
    {
        prop: 'created_at',
        label: '下单时间',
        minWidth: 175
    },
    {
        prop: 'operate',
        label: '操作',
        width: 295,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }) {
            return (
                <>
                    <ElButton
                        size="small"
                        onClick={() => {
                            router.push({
                                path: '/salesleads/salesmanagement/ordermanagement/neworder',
                                query: { type: 'look', id: row.id }
                            });
                        }}>
                        查看
                    </ElButton>
                    {row.edit_power == 1 ? (
                        <ElButton
                            size="small"
                            onClick={() => {
                                router.push({
                                    path: '/salesleads/salesmanagement/ordermanagement/neworder',
                                    query: { type: 'edit', id: row.id }
                                });
                            }}>
                            编辑
                        </ElButton>
                    ) : (
                        ''
                    )}

                    <ElButton
                        size="small"
                        onClick={() => {
                            router.push({
                                path: '/salesleads/salesmanagement/ordermanagement/detail',
                                query: { id: row.id }
                            });
                        }}>
                        详情
                    </ElButton>
                    {row.submit_button ? (
                        <ElButton
                            size="small"
                            onClick={() => {
                                onAudit(row);
                            }}>
                            提交审核
                        </ElButton>
                    ) : (
                        ''
                    )}
                </>
            );
        }
    }
];
const fetchApi = () => {
    // 获取文件列表
    getTableH();
    return orderGetList;
};
// 选中表格 checkbox
const onSelect = (selection, row) => {
    if (selection.constructor === Array) checkList.value = selection.map(v => v.id);
};
// 选择项变更
const onSelectionChange = selection => {};
// 全选
const onSelectAll = selection => {
    checkList.value = selection.map(v => v.id);
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};
// 导出表格数据
const exportTableData = () => {};
//跳转详情
const ondetail = (id: string) => {
    router.push('/salesleads/salesmanagement/ordermanagement/detail?id=' + id);
};
// 表格的自适应高度
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH(175);
    });
};
onMounted(() => {
    reSize(getTableH);
});
const tableTotal = ref(0);
defineExpose({
    reloadTable
});

onActivated((val: any) => {
    if (props.activeName === 'OrderList') {
        state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
    }
});
</script>

<style lang="scss" scoped>
.order_list_container {
    height: calc(100vh - 232px);
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

:deep(.imgslist) {
    display: flex;

    .name {
        color: #33302d;
        font-size: 14px;
        text-align: left;
        margin-left: 5px;
        width: 120px;

        p {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }

        .many {
            color: #969696;
            font-size: 12px;
        }
    }
}

:deep(.contacts) {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
}
</style>
